﻿using MediatR;
using Process.Api.Application.Command.BOM;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Infastructure;
using Process.Model;

namespace Process.Api.Application.Handler.BOM
{
    public class CreateBomHandler : IRequestHandler<CreateBomCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<BomTable> bomRepo;
        private readonly IProcessRepository<BomGoodsRelation> goodsrelationRepo;
        private readonly IProcessRepository<BomFlowRelation> flowrelationRepo;
        private readonly ProcessDbContext _db;

        public CreateBomHandler(IProcessRepository<BomTable> bomRepo, 
            IProcessRepository<BomGoodsRelation> goodsrelationRepo, 
            IProcessRepository<BomFlowRelation> flowrelationRepo,
            ProcessDbContext db)
        {
            this.bomRepo = bomRepo;
            this.goodsrelationRepo = goodsrelationRepo;
            this.flowrelationRepo = flowrelationRepo;
            this._db = db;
        }

        /// <summary>
        /// Bom新增
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(CreateBomCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 1. 验证BOM编号唯一性
                var existingBom =bomRepo.GetAllAsync();
                if (existingBom.Any(x => x.BOMCode == request.BOMCode))
                {
                    return new ApiResult<int>
                    {
                        Code = ErrorStatus.Error,
                        Message = "BOM编号已存在",
                        Data = 0
                    };
                }

                // 2. 创建BOM主表记录
                var bomTable = new BomTable
                {
                    BOMCode = request.BOMCode,
                    BOMTitle = request.BOMTitle,
                    ProductGoodsId = request.ProductGoodsId,
                    ProductsCode = request.ProductsCode,
                    ProductsName = request.ProductsName,
                    ProductsModel = request.ProductsModel,
                    ProductsUnit = request.ProductsUnit,
                    Brand = request.Brand,
                    Status = request.Status,
                    Version = request.Version,
                    Output = request.Output,
                    Desc = request.Desc,
                    CreateTime = DateTime.Now
                };

                // 3. 使用事务确保原子性操作
                await using var tx = await _db.Database.BeginTransactionAsync(cancellationToken);
                try
                {
                    // 创建BOM主表
                    var bomId = await bomRepo.CreateAsync(bomTable);
                    if (bomId <= 0)
                    {
                        await tx.RollbackAsync(cancellationToken);
                        return new ApiResult<int>
                        {
                            Code = ErrorStatus.Error,
                            Message = "创建BOM主表失败",
                            Data = 0
                        };
                    }

                    // 4. 创建配件关系记录
                    if (request.GoodsRelations != null && request.GoodsRelations.Any())
                    {
                        foreach (var goodsRel in request.GoodsRelations)
                        {
                            var bomGoodsRelation = new BomGoodsRelation
                            {
                                BomTableId = bomId,
                                GoodsinfoId = goodsRel.GoodsinfoId,
                                CreateTime = DateTime.Now
                            };
                            await goodsrelationRepo.CreateAsync(bomGoodsRelation);
                        }
                    }

                    // 5. 创建工艺流程关系记录
                    if (request.FlowRelations != null && request.FlowRelations.Any())
                    {
                        foreach (var flowRel in request.FlowRelations)
                        {
                            var bomFlowRelation = new BomFlowRelation
                            {
                                BomTableId = bomId,
                                ProcessFlowId = flowRel.ProcessFlowId,
                                CreateTime = DateTime.Now
                            };
                            await flowrelationRepo.CreateAsync(bomFlowRelation);
                        }
                    }

                    // 6. 提交事务
                    await _db.SaveChangesAsync(cancellationToken);
                    await tx.CommitAsync(cancellationToken);

                    return new ApiResult<int>
                    {
                        Code = ErrorStatus.Success,
                        Message = "BOM创建成功",
                        Data = bomId
                    };
                }
                catch (Exception ex)
                {
                    await tx.RollbackAsync(cancellationToken);
                    return new ApiResult<int>
                    {
                        Code = ErrorStatus.Error,
                        Message = $"创建BOM失败: {ex.Message}",
                        Data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ErrorStatus.Fail,
                    Message = $"系统错误: {ex.Message}",
                    Data = 0
                };
            }
        }
    }
}
